package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 鉴权过滤器 验证token
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.从交换机获取请求
        ServerHttpRequest request = exchange.getRequest();
        //2.从交换机获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3.如果是登陆请求则放行,其他的一律拦截
        //获取请求,然后判断是否包含登陆请求的关键字
        if (request.getURI().getPath().contains("/admin/login")) {
            //直接放行
            return chain.filter(exchange);
        }
        //4.获取请求头,来取出token来进行校验token
        HttpHeaders headers = request.getHeaders();
        //5.请求头中获取token
        String jwtToken = headers.getFirst("token");
        //6.判断请求头中是否有携带token
        if (StringUtils.isEmpty(jwtToken)) {
            //如果不存在,则向客户端返回相对应错误信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //未经授权
            //返回响应
            return response.setComplete();
        }
        //6.1 如果令牌存在,解析jwtToken令牌,判断该令牌是否合法,如果不合法,则向客户端返回相应的错误提示信息
        try {    //解析令牌
            JwtUtil.parseJWT(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            //令牌解析失败向客户端返回错误信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6.2 如果令牌合法,则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
